package com.example.chatchatbackend.handler;

import com.example.chatchatbackend.entity.vo.request.NoticeVO;
import com.example.chatchatbackend.entity.vo.response.SendNoticeVO;
import com.example.chatchatbackend.service.NoticeService;
import com.example.chatchatbackend.service.sendJob.SendNoticeService;
import com.example.chatchatbackend.utils.TimeUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class NoticeHandler {

    @Resource
    private NoticeService advService; // 假设有一个服务类用于处理数据库操作

    @Resource
    private SendNoticeService sendNoticeService;

    private static final LocalDateTime currentTime = TimeUtil.Time_Now.getCurrentTime();

    @XxlJob("noticeTaskHandler")
    public void execute() {

        XxlJobHelper.log("Xxl-Job:Insert");

        // 查询发送时间小于当前时间且未发送的任务
        List<SendNoticeVO> tasksToSend = sendNoticeService.findTasksToSend(this.currentTime);
        if(tasksToSend.isEmpty()){
            XxlJobHelper.log("无需更新，所有记录已发送");
            return;
        }

        SendNoticeVO sendNoticeVO = tasksToSend.get(0);

        NoticeVO advVO = new NoticeVO();
        BeanUtils.copyProperties(sendNoticeVO, advVO);

        advService.insertNotice(advVO);
        sendNoticeVO.setIsSend(1);
        sendNoticeService.updateSendNotice(sendNoticeVO);
        XxlJobHelper.log("成功插入Notice：{}",advVO);


    }
}
